package org.basis.algorithm.promote;

import java.util.Stack;

/**
 * 利用两个栈实现队列
 *
 * @author Mr_wenpan@163.com 2022/02/21 17:44
 */
public class StackImplementQueue {

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.add("wenpan");
        myQueue.add("hello");
        myQueue.add("world");
        myQueue.add("1");
        myQueue.add("2");
        myQueue.add("3");
        while (!myQueue.isEmpty()) {
            String peek = myQueue.peekFirst();
            System.out.println(peek);
            String str = myQueue.pollFirst();
            System.out.println(str);
        }

        System.out.println(myQueue.pollFirst());
    }

}

class MyQueue {

    private Stack<String> stack1;
    private Stack<String> stack2;

    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public boolean isEmpty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    /**
     * 元素入队列
     */
    public void add(String value) {
        stack2.push(value);
    }

    /**
     * 获取队列头元素，但不出队列
     */
    public String peekFirst() {
        if (stack2.isEmpty()) {
            return stack1.peek();
        }
        while (!stack2.isEmpty()) {
            String pop = stack2.pop();
            stack1.push(pop);
        }
        return stack1.peek();
    }

    /**
     * 获取队列头元素
     */
    public String pollFirst() {
        if (stack2.isEmpty()) {
            return stack1.pop();
        } else {
            while (!stack2.isEmpty()) {
                String pop = stack2.pop();
                stack1.push(pop);
            }
            return stack1.pop();
        }
    }

}
